#!/usr/local/bin/perl -w
use strict;
use utf8;
use open qw(:std :utf8);

use lib '../lib';

use NG::Gen::App 'NG::Sys::Loop::Run';
use Data::Dumper;
$Data::Dumper::Deparse = 1;
use Test::More 'no_plan';

use NG::Sys::Cfg;

my $app = new NG::Gen::App;

$app->run;

sub on_process {
	$app->{cfg}{db}{two} = config("db_test");
	my $dbh = $app->dbh_to("two");
	$app->users($dbh);
	$app->users->{cache}->clear;
	install($dbh);
	ok !$dbh->row_hash("select * from `user_logins"),"empty table user_logins";
	ok !$dbh->row_hash("select * from `user_online"),"empty table user_online";
	ok !$dbh->row_hash("select * from `user_sessions"),"empty table user_sessions";
	ok !$dbh->row_hash("select * from `user_registrations"),"empty user_registrations";

	my $user = $app->users->create_user("127.0.0.1",undef);
	ok $user,"create user";

	my $ses = $user->do_user_login("127.0.0.1");
	ok $ses,"create sesssion";

	ok my $reg = $dbh->row_hash("select * from `user_registrations"),"get user_registrations";
	is $reg->{user_id},$user->obj_id,"user_id";
	is $reg->{login},$user->login,"login";
	is $reg->{reg_ip},$user->reg_ip,"reg_ip";
	is $reg->{reg_ip},"127.0.0.1","reg_ip";
	is $reg->{reg_date},$user->reg_date,"reg_date";

	ok my $log = $dbh->row_hash("select * from `user_logins"),"get user_logins";
	is $log->{user_id},$user->obj_id,"user_id";
	is $log->{title},$user->title,"title obj";
	is $log->{title},"Гость","title str";
	is $log->{session},$ses,"session";
	is $log->{session_ip},"127.0.0.1","session ip";


	sleep 1;
	$user->do_user_logout;
	my $fu = $user->obj_id;

	ok $user = $app->users->create_user("127.0.0.1",$fu),"new user";
	ok $ses = $user->do_user_login("127.0.0.1"),"new session";
	ok $user->validate_user("test","123"),"user validated";
	ok $user->check_session($ses),"session valid";
	sleep 1;
	ok $user->check_online,"online checked";
	ok $user->do_user_logout,"user logout";
	sleep 1;
	ok $user = $app->users->get_by_login("test"),"user found";
	ok $user->check_password("123"),"password right";
	ok $ses = $user->do_user_login("127.0.0.1"),"get session";
	ok $user->check_session($ses),"session valid";
	sleep 1;
	ok $user->check_online,"online checked";
	ok $user->do_user_logout,"logout";
}
sub install {
	my $dbh = shift;
	my $sql = config("users_install")->{sql};
	for(@$sql){
		$dbh->exec($_);
	}
}
